//
//  NetworkTools.swift
//  Swift测试AFNetworking
//
//  Created by 伍银荣 on 2021/12/22.
//  Copyright © 2021 com.WYR. All rights reserved.
//

import UIKit
import AFNetworking

enum RequestMethod: String {
    case GET = "GET"
    case POST = "POST"
}

// MARK: - 网络工具
class NetworkTools: AFHTTPSessionManager {
    //单例
    static let sharedTools: NetworkTools = {
       let tools = NetworkTools(baseURL: URL(string: "http://httpbin.org/"))
        //设置反序列化数据格式
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        return tools
    }()
}

//MARK: - 封装 AFN 网络方法
extension NetworkTools {
    
    func request(method:RequestMethod, URLString: String, parameters: [String: Any]?, headers: [String: String]?, progress downloadProgress: ((Progress) -> Void)?, finished: @escaping (_ result: Any?, _ error: Error?) -> Void) {
        //定义成功回调
        let success = { (task: URLSessionDataTask, result: Any?) -> Void in
            finished(result, nil)
        }
        // 定义失败回调
        let failure = { (task: URLSessionDataTask?, error: Error) -> Void in
            finished(nil, error)
        }
        if method == RequestMethod.GET {
            get(URLString, parameters: parameters, headers: headers, progress: downloadProgress, success: success, failure: failure)
        } else {
            post(URLString, parameters: parameters, headers: headers, progress: downloadProgress, success: success, failure: failure)
        }
        
//        if method == RequestMethod.GET {
//            get(URLString, parameters: parameters, headers: headers, progress: downloadProgress, success: { (_, result) in
//                finished(result, nil)
//            }) { (_, error) in
//                print("error is \(error)")
//                finished(nil, error)
//            }
//        } else {
//            post(URLString, parameters: parameters, headers: headers, progress: downloadProgress, success: { (_, result) in
//                finished(result, nil)
//            }) { (_, error) in
//                print("error is \(error)")
//                finished(nil, error)
//            }
//        }
    }
//    override func get(_ URLString: String, parameters: Any?, headers: [String : String]?, progress downloadProgress: ((Progress) -> Void)?, success: ((URLSessionDataTask, Any?) -> Void)?, failure: ((URLSessionDataTask?, Error) -> Void)? = nil) -> URLSessionDataTask? {
//        <#code#>
//    }
}


